<?php

namespace Yearnfar\Bundle\BlogBundle\Controller;

use Doctrine\ORM\Query\ResultSetMapping;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Yearnfar\Bundle\BlogBundle\Entity\calendar;
use Yearnfar\Bundle\BlogBundle\Entity\user;
use Yearnfar\Bundle\BlogBundle\Exception\ShowMsgException;

/**
 * @Route("/admin")
 * @Template()
 */
class AdminController extends BaseController
{
    /**
     * @Route("/")
     * @Template()
     */
    public function indexAction()
    {
        return array(
                // ...
            );
    }

    /**
     * @Route("/login")
     * @Template()
     */
    public function loginAction()
    {
        return array();
    }

    /**
     * @Route("/login/check")
     * @Template()
     */
    public function loginCheckAction()
    {
        return array();
    }

    /**
     * @Route("/logout")
     * @Template()
     */
    public function logoutAction()
    {
        return array();
    }

    /**
     * @Route("/register")
     * @Template()
     */
    public function registerAction()
    {
        $post = $this->get('request')->request;

        $username = $post->get('username');
        $password = $post->get('password');
        $email    = $post->get('email');

        $rsm = new ResultSetMapping();
        $rsm->addEntityResult('Yearnfar\Bundle\BlogBundle\Entity\user', 'calendar')
            ->addFieldResult('calendar', 'username', 'username')
            ->addFieldResult('calendar', 'email',     'email');
        //
        $em  = $this->getDoctrine()->getEntityManager();
        $ret = $em->createNativeQuery('SELECT * FROM user WHERE username = ? OR email= ? LIMIT 1', $rsm)
                  ->setParameter(1, $username)
                  ->setParameter(2, $email)
                  ->getArrayResult();

        if ($ret) {
            $ret = array_shift($ret);
            if ($ret['email']==$email) {
                $this->showMsg("email已被注册！");
            } elseif ($ret['username']==$username) {
                $this->showMsg("昵称已被注册！");
            } else {
                $this->showMsg("注册失败！");
            }
        }

        $o = new user();
        $o ->setUsername($username)
           ->setPassword($this->get('security.password_encoder')->encodePassword($o, $password))
           ->setEmail($email)
           ->setRoles('ROLE_ADMIN')
           ->setAvatar('');

        $em->persist($o);
        $em->flush();

        $this->showMsg("注册成功！");

        return array();
    }

    /**
     * @Route("/calendar")
     * @Template()
     */
    public function calendarAction()
    {
        $req   = $this->get('request');
        $query = $req->query;

        $oper  = $query->get('oper',  '');
        $id    = $query->get('id',     0);
        $title = $query->get('title', '');
        $start = $query->get('start',  0);
        $end   = $query->get('end',    0);
        $allDay= $query->get('allDay', 1);
        $class = $query->get('class', '');

        $em   = $this->getDoctrine()->getManager();
        $uid  = $this->getUser()->getId();
        $list = array();

        switch ($oper) {
            case 'fetch':
                $rsm = new ResultSetMapping();
                $rsm->addEntityResult('Yearnfar\Bundle\BlogBundle\Entity\calendar', 'calendar')
                    ->addFieldResult('calendar', 'id',        'id')
                    ->addFieldResult('calendar', 'title',     'title')
                    ->addFieldResult('calendar', 'start',     'start')
                    ->addFieldResult('calendar', 'end',       'end')
                    ->addFieldResult('calendar', 'allDay',    'allDay')
                    ->addFieldResult('calendar', 'className', 'className');
                //
                $nq = $em->createNativeQuery('SELECT * FROM calendar WHERE uid = ? and start >= ? and end<= ? ', $rsm);
                $nq->setParameter(1, $uid)
                   ->setParameter(2, $start)
                   ->setParameter(3, $end);

                $list = $nq->getArrayResult();
                if ($list) {
                    foreach ($list as $key => $val) {
                        $list[$key]['start'] = date('Y-m-d H:i', $val['start']);
                        $list[$key]['end']   = date('Y-m-d H:i', $val['end']);
                    }
                } else {
                    $list = array();
                }
                break;
            case 'add'  :
                $o = new calendar();
                $o->setUid($uid)
                  ->setTitle($title)
                  ->setStart($start)
                  ->setEnd($end)
                  ->setAllday($allDay)
                  ->setClass($class);
                //
                $em->persist($o);
                $em->flush();
                break;
            case 'edit' :
                $o = $em->find('Yearnfar\Bundle\BlogBundle\Entity\calendar', $id);
                if ($o && $o->getUid()==$uid) {
                    $o->setTitle($title);
                    $o->setStart($start);
                    $o->setEnd($end);
                    $o->setAllDay($allDay);

                    $em->persist($o);
                    $em->flush();
                }
                break;
            case 'del'  :
                $o = $em->find('Yearnfar\Bundle\BlogBundle\Entity\calendar', $id);
                if ($o  && $o->getUid()==$uid) {
                    $em->remove($o);
                    $em->flush();
                }
                break;
            default     :
                break;
        }

        return array('data' => json_encode($list));
    }
}
